package com.weme.mine.activity

import android.app.AlertDialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ShapeDrawable
import android.graphics.drawable.shapes.RectShape
import android.media.MediaMetadataRetriever
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.QuickViewHolder
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.jeremyliao.liveeventbus.LiveEventBus
import com.makeramen.roundedimageview.RoundedImageView
import com.weme.common.activity.LookBigImgActivity
import com.weme.common.arouter.ARouterPaths
import com.weme.common.base.BaseMvvmActivity
import com.weme.common.util.*
import com.weme.common.util.AppMkHelper.IsOneAge
import com.weme.common.view.BottomSelectionDialog
import com.weme.common.view.BottomSelectionListener
import com.weme.common.view.SelectionItem
import com.weme.common.view.SmoothConstraintLayout
import com.weme.common.view.SmoothImageView
import com.weme.mine.R
import com.weme.mine.bean.AlbumBean
import com.weme.mine.bean.StroyBean
import com.weme.mine.databinding.ActivityEdUserinfoBinding
import com.weme.mine.dialog.*
import com.weme.mine.viewmode.EdUserInfoViewMode
import dev.kratos.api.user_server.v1.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.File


@Route(path = ARouterPaths.MINE_ED_USERINFO_ACTIVITY)
class EdUserInfoActivity : BaseMvvmActivity<ActivityEdUserinfoBinding, EdUserInfoViewMode>() {
    var myGender = 0
    private val albumList = mutableListOf<AlbumBean>()
    private val srtoyList = mutableListOf<StroyBean>()
    private lateinit var alertDialog: AlertDialog
    var user: Users? = null
    val uploader: AwsS3Uploader by lazy {
        AwsS3Uploader.getInstance(this)
    }

    override fun initView(savedInstanceState: Bundle?) {
        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR).titleBar(mBinding.customTopNavigationBar).init()
        alertDialog = createProgressDialog()
        initStroyAdapter()
        initAlbumAdapter()
        initOnclick()

        viewModel.getAlubm(GetAlbumRequest.newBuilder().build())
        viewModel.getMseeageList(GetUserInfoRequest.newBuilder().build())
        LiveEventBus.get<Any>(LiveConfig.NET_WORK_ED_USER_IFNO).observe(this) {
            if (it is Users) {
                user = it
                mBinding.edName.text = it.nickname
                mBinding.edGende.text = if (it.gender == 1) getString(com.example.resources.R.string.male) else getString(com.example.resources.R.string.female)
                if (it.gender != 1) {
                    mBinding.edGende.setTextColor(Color.parseColor("#80ffffff"))
                    mBinding.edGende.clearDrawableRight()
                    mBinding.clickGender.setOnClickListener { }
                }
                mBinding.edAge.text = it.age.toString()
                if (UserMKHelper.decodeBoolean(IsOneAge)) {
                    mBinding.edAge.clearDrawableRight()
                    mBinding.edAge.setTextColor(Color.parseColor("#80ffffff"))
                    mBinding.edAge.invalidate()
                }
                mBinding.edAbout.text = it.intro
            }
            if (it is UploadAlbumReply) {
                it.mediaList.forEach {
                    if (it.type.isTypeImg()) {
                        if (TextUtils.isEmpty(albumList[0].imgUrl)) {
                            albumList[1].id = it.id
                        } else if (albumList.size > 5) {
                            albumList[0].id = it.id
                        }
                        val containsType9 = albumList.any { it.type == 7 }
                        if (!containsType9) {
                            val firstMatchingAlbum = albumList.find { !TextUtils.isEmpty(it.imgUrl) }
                            if (firstMatchingAlbum != null) {
                                firstMatchingAlbum.type = 7
                            }
                        } else {
                            var isHead = true
                            albumList.forEach {
                                if (!TextUtils.isEmpty(it.imgUrl) && isHead) {
                                    isHead = false
                                    it.type = 7 //         return@forEach
                                } else {
                                    it.type = 1 //       return@forEach
                                }
                            }
                        }


                    } else if (!it.type.isTypeImg()) {
                        if (TextUtils.isEmpty(srtoyList[0].imgUrl)) {
                            srtoyList[1].id = it.id
                        } else if (srtoyList.size >= 3) {
                            srtoyList[0].id = it.id
                        }
                    }
                }
                alertDialog.dismiss()
                ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR).init()
                showToast(getString(com.example.resources.R.string.toast_success))
                Log.e("socket", "上传成功" + it.mediaCount)
            }
            if (it is GetAlbumReply) {
                val imgList = it.mediaList.filter { it.type.isTypeImg() }
                val videoList = it.mediaList.filter { !it.type.isTypeImg() }
                albumList.clear()
                if (imgList.isEmpty()) {
                    albumList.addAll(listOf(AlbumBean(""), AlbumBean(""), AlbumBean(""), AlbumBean(""), AlbumBean(""), AlbumBean("")))
                } else if (imgList.size >= 6) {
                    imgList.forEachIndexed { _, media ->
                        albumList.add(AlbumBean(media.url, id = media.id))
                    }
                } else {
                    albumList.add(AlbumBean(""))
                    imgList.forEachIndexed { _, media ->
                        albumList.add(AlbumBean(media.url, id = media.id))
                    }
                    for (i in albumList.size..5) {
                        albumList.add(AlbumBean(""))
                    }
                }
                val containsType9 = imgList.any { it.type == 7 }

                if (!containsType9) {
                    val firstMatchingAlbum = albumList.find { !TextUtils.isEmpty(it.imgUrl) }
                    if (firstMatchingAlbum != null) {
                        firstMatchingAlbum.type = 7
                    }
                }


                albumAdapter.notifyDataSetChanged()
                srtoyList.clear()
                if (videoList.isEmpty()) {
                    srtoyList.addAll(listOf(StroyBean("")))
                } else if (videoList.size >= 3) {
                    videoList.forEachIndexed { _, media ->
                        srtoyList.add(StroyBean(media.url, id = media.id))
                    }
                } else {
                    srtoyList.add(StroyBean(""))
                    videoList.forEachIndexed { _, media ->
                        srtoyList.add(StroyBean(media.url, id = media.id))
                    }
                }
                stroyAdapter.notifyDataSetChanged()
            }
        }


    }


    override fun onResume() {
        super.onResume() //        setScreenWidthHeight()
        //        AutoSize.autoConvertDensityOfCustomAdapt(this, this)
    }


    private fun initStroyAdapter() {
        mBinding.rcvStroy.adapter = stroyAdapter
//
//        val dividerItemDecoration = DividerItemDecoration(this, resources.getDimensionPixelOffset(com.example.resources.R.dimen.dp_12))
//        mBinding.rcvStroy.addItemDecoration(dividerItemDecoration)

        val shapeDrawable = ShapeDrawable(RectShape()).apply {
            intrinsicHeight = resources.getDimensionPixelSize(com.example.resources.R.dimen.dp_12) // 设置分割线的高度
            paint.color = ContextCompat.getColor(this@EdUserInfoActivity, com.weme.common.R.color.transparent) // 设置分割线的颜色
        }

        // 设置分割线的方向
        val orientation = RecyclerView.HORIZONTAL // 或者 RecyclerView.HORIZONTAL

        // 创建 DividerItemDecoration 对象
        val dividerItemDecoration = DividerItemDecoration(this, orientation).apply {
            setDrawable(shapeDrawable)
        }

        // 添加分割线到 RecyclerView
        mBinding.rcvStroy.addItemDecoration(dividerItemDecoration)

        srtoyList.addAll(listOf(StroyBean("")))
        stroyAdapter.submitList(srtoyList)
    }


    private val stroyAdapter = object : BaseQuickAdapter<StroyBean, QuickViewHolder>() {
        override fun onBindViewHolder(holder: QuickViewHolder, position: Int, item: StroyBean?) {
            val imView = holder.getView<RoundedImageView>(R.id.imView)
            if (position == 0 && TextUtils.isEmpty(item!!.imgUrl)) {
                holder.setVisible(R.id.imView, false)
                holder.setVisible(R.id.imBg, true)
                holder.setVisible(R.id.imAdd, true)
                val imAdd = holder.getView<ImageView>(R.id.imAdd)
                imAdd.setOnClickListener {
                    showPhoto(1)
                }
            } else {
                holder.setVisible(R.id.imView, true)
                holder.setVisible(R.id.imBg, true)
                holder.setVisible(R.id.imAdd, false)
                imView.loadImage(item!!.imgUrl)
                imView.setOnClickListener {
                    toBigActivity(item.imgUrl, false)

                }

            }


        }

        override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): QuickViewHolder {
            return QuickViewHolder(R.layout.item_edinfo_stroy, parent)
        }


    }


    private fun initAlbumAdapter() {
        mBinding.rcvAlbum.adapter = albumAdapter
        albumList.addAll(listOf(AlbumBean(""), AlbumBean(""), AlbumBean(""), AlbumBean(""), AlbumBean(""), AlbumBean("")))
        albumAdapter.submitList(albumList) //  albumAdapter.notifyDataSetChanged()
    }

    private val albumAdapter = object : BaseQuickAdapter<AlbumBean, QuickViewHolder>() {

        override fun onBindViewHolder(holder: QuickViewHolder, position: Int, item: AlbumBean?) {
            val simView = holder.getView<SmoothImageView>(R.id.simView)
            val simViewMc = holder.getView<SmoothConstraintLayout>(R.id.simViewMc)
            simViewMc.setVisible(position == 0 && TextUtils.isEmpty(item!!.imgUrl))
            simView.setVisible(simViewMc.visibility == View.GONE)
            if (position == 0 && TextUtils.isEmpty(item!!.imgUrl)) {
                simView.setImageResource(0)
                simView.setOnClickListener {
                    showPhoto(2)
                }
            } else if (TextUtils.isEmpty(item!!.imgUrl)&&position != 0 ) {
                simView.setImageResource(com.example.resources.R.drawable.bg_photo_null)
            } else {
                simView.loadImage(item.imgUrl)
                simView.setOnClickListener {
                    toBigActivity(item.imgUrl, true)
                }
            }


        }

        override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): QuickViewHolder {
            return QuickViewHolder(R.layout.item_album, parent)
        }


    }

    fun showPhoto(type: Int) {
        val selectionItems = listOf(
            SelectionItem(getString(com.example.resources.R.string.authentication_aboutme_camera), 0, object : BottomSelectionListener {
                override fun onTitleClicked(position: Int) {

                    if (type == 1) {
                        MediaUtils.captureVideo(this@EdUserInfoActivity) {
                            if (it == "start") {
                                alertDialog.show()
                            } else {
                                uploadVideo(it)
                            }
                        }
                    } else {
                        MediaUtils.captureImage(this@EdUserInfoActivity) {
                            alertDialog.show()
                            uploadImage(it)
                        }
                    }


                }

            }),
            SelectionItem(getString(com.example.resources.R.string.authentication_aboutme_gellery), 1, object : BottomSelectionListener {
                override fun onTitleClicked(position: Int) {

                    if (type == 1) {
                        MediaUtils.selectVideos(this@EdUserInfoActivity, 1) {
                            if (it == "start") {
                                alertDialog.show()
                            } else {
                                uploadVideo(it)
                            }

                        }
                    } else {
                        MediaUtils.selectImages(this@EdUserInfoActivity, 1) {
                            alertDialog.show()
                            uploadImage(it)
                        }
                    }

                }
            }),
        )


        val btndialog = BottomSelectionDialog.newInstance(selectionItems)
        btndialog.show(this.supportFragmentManager,"")
    }

    fun uploadImage(imageUrl: String) {
        upDataAws(imageUrl, 1)
    }

    fun toBigActivity(url: String, isImg: Boolean) {
        val items = mutableListOf<Media>()
        var position = 0
        if (isImg) {
            albumList.forEach {
                if (!TextUtils.isEmpty(it.imgUrl)) {
                    val media1 = Media.newBuilder().setType(1).setUrl(it.imgUrl).setId(it.id).build()
                    items.add(media1) // items.add(AlbumBean(it.imgUrl, type = 1, id = it.id,url = it.imgUrl))
                }
                if (url == it.imgUrl) {
                    position = items.size - 1
                }
            }
        } else {
            srtoyList.forEach {
                if (!TextUtils.isEmpty(it.imgUrl)) {
                    val media1 = Media.newBuilder().setType(2).setUrl(it.imgUrl).setId(it.id).build()
                    items.add(media1) // items.add(AlbumBean(it.imgUrl, type = 2, id = it.id,url = it.imgUrl))
                }
                if (url == it.imgUrl) {
                    position = items.size - 1
                }
            }
        }



        user?.let { it1 ->
            val userBuilder = Users.newBuilder()
            user?.let { it1 ->
                userBuilder.uid = it1.uid
                userBuilder.nickname = it1.nickname
                userBuilder.age = it1.age
                userBuilder.setCountryCode(it1.countryCode)
            }

            userBuilder.addAllMedia(items)
            LookBigImgActivity.openActivity(this@EdUserInfoActivity, userBuilder.build(), position, resultLauncher)
        }
    }

    private val resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        viewModel.getAlubm(GetAlbumRequest.newBuilder().build()) //        it.data?.run {
        //
        //        }
    }

    fun uploadVideo(videoUrl: String) {
        if (getVideoDuration(videoUrl) < 5000) {
            this@EdUserInfoActivity.showToast(getString(com.example.resources.R.string.video_error))
            alertDialog.dismiss()
            ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR).init()
            return
        }
        upDataAws(videoUrl, 2)

    }


    private fun getVideoDuration(videoPath: String): Long {
        val retriever = MediaMetadataRetriever()
        retriever.setDataSource(videoPath)

        // 获取时长（单位：毫秒）
        val durationStr = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)

        // 转换为 long 类型
        var duration: Long = 0
        try {
            duration = durationStr!!.toLong()
        } catch (e: NumberFormatException) {
            e.printStackTrace()
        }

        // 释放资源
        retriever.release()
        return duration
    }


    private fun upDataAws(imageUrl: String, type: Int) {


        uploader.setUploadListener(object : AwsS3Uploader.UploadListener {
            override fun onProgressChanged(progress: Int) { // 可以通过 uploadSubject.onNext(progress) 发送上传进度
            }

            override fun onUploadComplete(url: String) {
                alertDialog.dismiss() // 触发隐藏对话框
                ImmersionBar.with(this@EdUserInfoActivity).hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR).init()
                GlobalScope.launch(Dispatchers.Main) {
                    if (type == 1) {
                        val newAlbumBean = AlbumBean(imageUrl)
                        if (TextUtils.isEmpty(albumList[albumList.size - 1].imgUrl)) {
                            albumList.add(1, newAlbumBean)
                            if (albumList[albumList.size - 1].imgUrl == "") {
                                albumList.removeAt(albumList.size - 1)
                            }
                        } else if (albumList.size > 5) {
                            albumList.removeAt(0)
                            albumList.add(0, newAlbumBean)
                        }
                        albumAdapter.notifyDataSetChanged()
                    } else {
                        val stroyBean = StroyBean(imageUrl)
                        if (srtoyList.size >= 3) {
                            srtoyList[0] = stroyBean
                        } else {
                            srtoyList.add(1, stroyBean)
                        }
                        stroyAdapter.notifyDataSetChanged()
                    }

                    val media = Media.newBuilder().setType(type).setUrl(url).build()
                    val uploader = UploadAlbumRequest.newBuilder().addMedia(media).build()
                    viewModel.uploaderApi(uploader)
                }
            }

            override fun onUploadFailed() {
                showToast(getString(com.example.resources.R.string.toast_video_error))
                alertDialog.dismiss() // 触发隐藏对话框
                ImmersionBar.with(this@EdUserInfoActivity).hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR).init()
            }
        })

        if (type == 1) {
            uploader.uploadImage(File(imageUrl))
        } else {
            uploader.uploadVideo(File(imageUrl))
        }
    }


    private fun initOnclick() {
        mBinding.clickName.setOnFastClickListener {
            val edNameDialog = EdNameDialog(this, 0, mBinding.edName.text.toString())
            edNameDialog.setEdNameDialogListener(object : EdNameDialogListener {
                override fun onNameEntered(name: String) {
                    mBinding.edName.text = name
                    viewModel.setUserInfoApi(EditUserInfoRequest.newBuilder().setNickname(name).build())
                }

            })
            edNameDialog.show()
        }
        mBinding.edAbout.setOnFastClickListener {
            val edNameDialog = EdNameDialog(this, 1, mBinding.edAbout.text.toString())
            edNameDialog.setEdNameDialogListener(object : EdNameDialogListener {
                override fun onNameEntered(name: String) {
                    mBinding.edAbout.text = name
                    viewModel.setUserInfoApi(EditUserInfoRequest.newBuilder().setIntro(name).build())
                }

            })
            edNameDialog.show()
        }
        mBinding.clickAge.setOnFastClickListener {
            if (UserMKHelper.decodeBoolean(IsOneAge)) {
                return@setOnFastClickListener
            }
            val ageDialog = EdAgeDialog(this, mBinding.edAge.text.toString())
            ageDialog.setEdAgeDialogListener(object : EdAgeDialogListener {
                override fun onAgeEntered(name: Int) {
                    UserMKHelper.encode(IsOneAge, true)
                    mBinding.edAge.clearDrawableRight()
                    mBinding.edAge.setTextColor(Color.parseColor("#80ffffff"))

                    mBinding.edAge.text = name.toString()
                    viewModel.setUserInfoApi(EditUserInfoRequest.newBuilder().setAge(name).build())
                    mBinding.edAge.invalidate()
                }

            })
            ageDialog.show()
        }
        mBinding.clickGender.setOnFastClickListener {
            val genderDialog = EdGenderDialog(this, mBinding.edGende.text.toString())
            genderDialog.setEdGenderDialogListener(object : EdGenderDialogListener {
                override fun onGenderEntered(gender: Int) {
                    myGender = gender
                    viewModel.setUserInfoApi(EditUserInfoRequest.newBuilder().setGender(gender).build())
                    mBinding.edGende.setTextColor(Color.parseColor("#80ffffff"))
                    mBinding.edGende.clearDrawableRight()
                    mBinding.clickGender.setOnClickListener { }
                    if (gender == 1) {
                        mBinding.edGende.text = getString(com.example.resources.R.string.male)
                    } else {
                        mBinding.edGende.text = getString(com.example.resources.R.string.female)
                    }
                }

            })
            genderDialog.show()
        }
    }

    override fun getViewModelClass(): Class<EdUserInfoViewMode> = EdUserInfoViewMode::class.java


    override fun onDestroy() {
        super.onDestroy()
        LoadingDailog.dismiss()

        uploader.clearUploadListener()
    }

    fun ImageView.loadImage(imageUrl: String?) {
        if (TextUtils.isEmpty(imageUrl)) {
            return
        }
        imageUrl?.apply {
            Glide.with(context).load(imageUrl).dontAnimate().sizeMultiplier(0.8f).override(180, 180) //  .diskCacheStrategy(DiskCacheStrategy.ALL) // 根据需求设置缓存策略
                .into(this@loadImage)
        }

    }
}